<?php
namespace app\utils;
use App;
class CspFilter extends \app\BaseObject{
	public static function formatSource($sources){
		$value = [];
		if(is_array($sources)){
			foreach($sources as $source){
				if(self::isNeed($source)){
					$value[] = "'{$source}'";
				}else{
					$value[] = (string)$source;
				}
			}
		}else{
			if(self::isNeed($sources)){
				$value[] = "'{$sources}'";
			}else{
				$value[] = "{$sources}";
			}
		}
		return implode(' ', $value);
	}
	public static function cspContent($contents){
		$arr = [];
		foreach ($contents as $key => $val) {
			$arr[] = $key . ' ' . self::formatSource($val);
		}
		return implode(';', $arr);
	}
	public static function isNeed($str){
		$need = ['self', 'unsafe-inline', 'unsafe-eval', 'none'];
		if(in_array($str, $need)){
			return true;
		}
		if( is_string($str) && strpos($str, 'nonce-')!==false ){
			return true;
		}
		
		return false;
	}
	public static function isValidDomain($domain) {
	    // 正则表达式匹配域名
	    $pattern = "/^([a-z0-9]([a-z0-9\-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9\-]{0,61}[a-z0-9]$/i";
	    return preg_match($pattern, $domain);
	}
	public static function isValidIP($ip) {
	    return filter_var($ip, FILTER_VALIDATE_IP) !== false;
	}
}